import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, message, Button, Spin, Alert } from 'antd';
import { adminApi } from '../../api/services/admin/admin';
import type { GetUserResponseData, UpdateUserRequest, UpdateUserStatusParams } from '../../api/dto/admin';

const { Option } = Select;

interface EditUserModalProps {
  open: boolean;
  userId: number | null;
  onCancel: () => void;
  onSuccess: () => void;
}

const EditUserModal: React.FC<EditUserModalProps> = ({ 
  open, 
  userId, 
  onCancel, 
  onSuccess 
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [userData, setUserData] = useState<GetUserResponseData | null>(null);
  
  // 检查用户是否被禁用
  const isDisabledUser = userData?.status === 0;

  // 获取用户信息
  useEffect(() => {
    if (!open || !userId) {
      setUserData(null);
      form.resetFields();
      return;
    }

    const fetchUserData = async () => {
      setLoading(true);
      try {
        const response = await adminApi.getUserById(userId);
        
        if (response.code === 200 && response.data) {
          const user = response.data;
          setUserData(user);
          form.setFieldsValue({
            name: user.name || '',
            username: user.username || '',
            email: user.email || '',
            phoneNumber: user.phone || '',
            profileId: user.role || '',
            systemRole: user.role?.toString() || '1',
            status: user.status?.toString() || '1',
          });
        } else {
          message.error(response.message || '获取用户信息失败');
          onCancel();
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        message.error('获取用户信息失败，请稍后再试');
        onCancel();
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, [open, userId, form, onCancel]);

  // 启用用户账号
  const handleEnableUser = async () => {
    try {
      setLoading(true);
      const params: UpdateUserStatusParams = {
        id: userId!.toString(),
        status: 1 
      };
      const response = await adminApi.updateUserStatus(params);

      if (response.code === 200) {
        message.success('用户已成功启用');
        onSuccess(); 
        onCancel(); 
      } else {
        message.error(response.message || '启用用户失败');
      }
    } catch (error) {
      console.error('启用用户失败:', error);
      message.error('启用用户失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单（用于非禁用状态的用户）
  const handleSubmit = async () => {
    try {
      await form.validateFields();
      const values = form.getFieldsValue();
      
      setLoading(true);
      
      const requestData: UpdateUserRequest = {
        id: userId!.toString(),
        name: values.name,
        username: values.username,
        email: values.email,
        phoneNumber: values.phoneNumber,
        profileId: values.profileId,
        systemRole: values.systemRole,
        status: values.status,
      };

      const response = await adminApi.updateUser(requestData);

      if (response.code === 200) {
        message.success('用户信息更新成功');
        onSuccess();
        onCancel();
      } else {
        message.error(response.message || '更新用户信息失败');
      }
    } catch (error) {
      console.error('更新用户失败:', error);
      message.error('更新用户信息失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={userData ? `编辑用户 ${userData.name}${isDisabledUser ? ' (已禁用)' : ''}` : '编辑用户'}
      open={open}
      onCancel={onCancel}
      footer={null}
      width={700}
      maskClosable={false}
    >
      {loading && !userData ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在加载用户信息...</div>
        </div>
      ) : (
        <>
          {isDisabledUser && (
            <Alert
              message="此用户已被禁用"
              description="禁用状态的用户无法编辑信息，您可以启用该用户账号。"
              type="warning"
              showIcon
              style={{ marginBottom: 24 }}
            />
          )}
          
          <Form
            form={form}
            layout="vertical"
            initialValues={userData || undefined}
          >
            <Form.Item
              label="姓名"
              name="name"
              rules={[
                { required: true, message: '请输入姓名' },
                { min: 2, max: 20, message: '姓名长度为2-20个字符' }
              ]}
            >
              <Input 
                placeholder="请输入用户姓名" 
                disabled={isDisabledUser || loading}
              />
            </Form.Item>

            <Form.Item
              label="用户名"
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 4, max: 20, message: '用户名为4-20个字符' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线' }
              ]}
            >
              <Input 
                placeholder="请输入用户名" 
                disabled={isDisabledUser || loading}
              />
            </Form.Item>

            <Form.Item
              label="学号/工号"
              name="profileId"
              rules={[
                { required: true, message: '请输入学号或工号' },
                { pattern: /^[A-Za-z0-9]+$/, message: '只能包含字母和数字' }
              ]}
            >
              <Input 
                placeholder="请输入学号或工号" 
                disabled={isDisabledUser || loading}
              />
            </Form.Item>

            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱格式' }
              ]}
            >
              <Input 
                placeholder="请输入邮箱地址" 
                disabled={isDisabledUser || loading}
              />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phoneNumber"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
              ]}
            >
              <Input 
                placeholder="请输入手机号" 
                disabled={isDisabledUser || loading}
              />
            </Form.Item>

            <Form.Item
              label="角色"
              name="systemRole"
              rules={[{ required: true, message: '请选择角色' }]}
            >
              <Select 
                placeholder="请选择用户角色"
                disabled={isDisabledUser || loading}
              >
                <Option value="1">学生</Option>
                <Option value="2">老师</Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="状态"
              name="status"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Select 
                placeholder="请选择用户状态"
                disabled={loading}
              >
                <Option value="0">禁用</Option>
                <Option value="1">启用</Option>
                <Option value="2">待验证</Option>
              </Select>
            </Form.Item>

            <Form.Item style={{ marginTop: 32 }}>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 16 }}>
                <Button onClick={onCancel} disabled={loading}>
                  取消
                </Button>
                
                {isDisabledUser ? (
                  <Button 
                    type="primary" 
                    onClick={handleEnableUser}
                    loading={loading}
                  >
                    {loading ? '启用中...' : '启用用户'}
                  </Button>
                ) : (
                  <Button 
                    type="primary" 
                    onClick={handleSubmit}
                    loading={loading}
                  >
                    {loading ? '保存中...' : '保存更改'}
                  </Button>
                )}
              </div>
            </Form.Item>
          </Form>
        </>
      )}
    </Modal>
  );
};

export default EditUserModal;